<!-- 商品详情页 -->
<template>
    <div class="product-detail">
        <!-- 返回按钮 -->
        <div class="back-button" @click="goBack">
            <span class="back-icon">←</span>
            <span class="back-text">返回官方商区</span>
        </div>

        <!-- 商品详情内容 -->
        <div class="detail-container" v-if="product">
            <div class="product-main">
                <!-- 左侧商品图片 -->
                <div class="product-image-section">
                    <img :src="product.img" :alt="product.name" class="product-image-up">
                </div>
                
                <!-- 右侧商品信息 -->
                <div class="product-info-section">
                    <h1 class="product-title">{{ product.name }}</h1>
                    
                    <div class="product-category">
                        <span class="category-label">分类：</span>
                        <span class="category-tag">{{ product.kind || '未分类' }}</span>
                    </div>
                    
                    <div class="product-price">
                        <span class="price-label">价格：</span>
                        <span class="price-value">¥{{ product.price }}</span>
                    </div>
                    
                    <div class="product-stock">
                        <span class="stock-label">库存：</span>
                        <span class="stock-value">{{ product.margin }} 件</span>
                    </div>
                    
                    <div class="product-description">
                        <h3 class="description-title">商品描述</h3>
                        <p class="description-text">{{ product.describe }}</p>
                    </div>
                    
                    <!-- 购买区域 -->
                    <div class="purchase-section">
                        <div class="quantity-selector">
                            <label class="quantity-label">购买数量：</label>
                            <div class="quantity-controls">
                                <button 
                                    class="quantity-btn" 
                                    @click="decreaseQuantity" 
                                    :disabled="quantity <= 1"
                                >
                                    -
                                </button>
                                <input 
                                    type="number" 
                                    v-model="quantity" 
                                    class="quantity-input" 
                                    min="1" 
                                    :max="product.margin"
                                    @change="validateQuantity"
                                />
                                <button 
                                    class="quantity-btn" 
                                    @click="increaseQuantity" 
                                    :disabled="quantity >= product.margin"
                                >
                                    +
                                </button>
                            </div>
                        </div>
                        
                        <div class="purchase-actions">
                            <button 
                                class="add-to-cart-btn" 
                                @click="addToCart"
                                :disabled="quantity > product.margin"
                            >
                                加入购物车
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 下方是子组件 -->
        <div class="product-filter-section" v-if="product">
            <div class="filter-container">
                <h3 class="filter-title">推荐商品</h3>
                <div class="category-tabs">
                    <div 
                        class="category-tab" 
                        :class="{ active: selectedCategory === '' }"
                        @click="selectCategory('')"
                    >
                        全部
                    </div>
                    <div 
                        class="category-tab" 
                        :class="{ active: selectedCategory === '影视' }"
                        @click="selectCategory('影视')"
                    >
                        影视
                    </div>
                    <div 
                        class="category-tab" 
                        :class="{ active: selectedCategory === '音乐' }"
                        @click="selectCategory('音乐')"
                    >
                        音乐
                    </div>
                </div>
            </div>
            
            <!-- 商品列表 -->
            <div class="filtered-products" v-if="filteredProducts.length > 0">
                <h4 class="results-title">{{ selectedCategory || '全部商品' }} ({{ filteredProducts.length }} 个商品)</h4>
                <div class="products-grid">
                    <div 
                        class="product-item" 
                        v-for="item in filteredProducts" 
                        :key="item.id"
                        @click="goToProduct(item.id)"
                    >
                        <div class="product-image">
                            <img :src="item.img" :alt="item.name" />
                        </div>
                        <div class="product-info">
                            <h5 class="product-name">{{ item.name }}</h5>
                            <p class="product-category">{{ item.kind }}</p>
                            <p class="product-price">¥{{ item.price }}</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 商品不存在 -->
        <div class="product-not-found" v-else>
            <div class="not-found-icon">😞</div>
            <h2>商品不存在</h2>
            <p>抱歉，您访问的商品不存在或已被删除</p>
            <button class="back-to-list-btn" @click="goBack">返回商品列表</button>
        </div>
    </div>
</template>

<script>
import { ref, computed, onMounted, getCurrentInstance } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'

export default {
    name: 'ProductDetail',
    setup() {
        const route = useRoute()
        const router = useRouter()
        const store = useStore()
        const { proxy } = getCurrentInstance()
        
        const quantity = ref(1)
        const selectedCategory = ref('')
        
        // 获取商品ID
        const productId = computed(() => parseInt(route.params.id))
        
        // 获取商品信息
        const product = computed(() => {
            return store.getters.allProducts.find(item => item.id === productId.value)
        })
        
        // 获取所有分类
        const categories = computed(() => {
            const categorySet = new Set()
            store.getters.allProducts.forEach(item => {
                if (item.kind) {
                    categorySet.add(item.kind)
                }
            })
            return Array.from(categorySet).sort()
        })
        
        // 筛选后的商品列表
        const filteredProducts = computed(() => {
            let products = store.getters.allProducts.filter(item => item.id !== productId.value)
            
            // 分类筛选
            if (selectedCategory.value) {
                products = products.filter(item => item.kind === selectedCategory.value)
            }
            
            return products
        })
        
        // 返回上一页
        const goBack = () => {
            router.push('/mycontents/official')
        }
        
        // 增加数量
        const increaseQuantity = () => {
            if (quantity.value < product.value.margin) {
                quantity.value++
            }
        }
        
        // 减少数量
        const decreaseQuantity = () => {
            if (quantity.value > 1) {
                quantity.value--
            }
        }
        
        // 验证数量
        const validateQuantity = () => {
            if (quantity.value < 1) {
                quantity.value = 1
            } else if (quantity.value > product.value.margin) {
                quantity.value = product.value.margin
                alert(`库存不足，最多只能选择${product.value.margin}件`)
            }
        }
        
        // 添加到购物车
        const addToCart = async () => {
            if (quantity.value < 1) {
                alert('请选择至少1件商品')
                return
            }
            if (quantity.value > product.value.margin) {
                alert(`库存不足，最多只能选择${product.value.margin}件`)
                return
            }
            
            try {
                // 构建给后端数据库的数据对象
                const goodobj = {
                    id: 0,//购物车记录ID
                    goodid: product.value.id,//商品ID
                    title: product.value.name,
                    price: product.value.price,
                    mydescribe: product.value.describe,
                    img: product.value.img,
                    num: quantity.value,
                    memo: product.value.memo || '',
                    clicknum: 0,
                    goodtype: product.value.kind || '',
                    createBy: store.state.loginName,//登录人姓名
                    remark: '',
                    status: '未提交'//状态
                }
                
                // 构建给 Vuex store 的数据对象（使用 store 期望的格式）
                const productForStore = {
                    id: product.value.id,
                    name: product.value.name,
                    price: product.value.price,
                    describe: product.value.describe,
                    img: product.value.img,
                    num: quantity.value
                }
                
                // 提交到后端数据库（如果需要）
                if (proxy && proxy.execdata) {
                    proxy.execdata('/system/cart', goodobj).then(response => {
                        console.log('添加成功：', goodobj);
                    }).catch(error => {
                        console.error('提交到后端失败：', error);
                    });
                }
               
                // 使用Vuex action添加商品到购物车（这会更新库存）
                await store.dispatch('addToCart', productForStore)
                
                // 获取更新后的商品信息
                const updatedProducts = store.getters.allProducts
                const updatedProduct = updatedProducts.find(item => item.id === product.value.id)
                
                if (updatedProduct) {
                    alert(`${product.value.name}成功加入购物车 ${quantity.value} 件商品，剩余库存：${updatedProduct.margin} 件`)
                } else {
                    alert(`${product.value.name}成功加入购物车 ${quantity.value} 件商品`)
                }
            } catch (error) {
                alert(error.message)
            }
        }
        
        // 选择分类
        const selectCategory = (category) => {
            selectedCategory.value = category
        }
        
        // 跳转到其他商品详情页
        const goToProduct = (productId) => {
            router.push(`/product/${productId}`)
        }
        
        return {
            product,
            quantity,
            selectedCategory,
            categories,
            filteredProducts,
            goBack,
            increaseQuantity,
            decreaseQuantity,
            validateQuantity,
            addToCart,
            selectCategory,
            goToProduct
        }
    }
}
</script>

<style scoped>
.product-detail {
    min-height: 100vh;
    background: linear-gradient(135deg, #e3f2fd 0%, #f0f8ff 100%);
    padding: 20px;
}

/* 返回按钮 */
.back-button {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 40px;
    padding: 10px 16px;
    background: rgba(255, 255, 255, 0.8);
    border: 1px solid #b3d9ff;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s ease;
    color: #1976d2;
    text-decoration: none;
    font-weight: 500;
}

.back-button:hover {
    background: rgba(255, 255, 255, 0.9);
    border-color: #1976d2;
    transform: translateX(-3px);
}

.back-icon {
    font-size: 16px;
    color: #1976d2;
}

.back-text {
    color: #1976d2;
    font-weight: 500;
}

/* 详情容器 */
.detail-container {
    max-width: 1000px;
    margin: 0 auto;
}

.product-main {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 60px;
    background: rgba(255, 255, 255, 0.6);
    padding: 40px;
    border-radius: 12px;
    border: 1px solid rgba(179, 217, 255, 0.3);
}

/* 商品图片区域 */
.product-image-section {
    display: flex;
    justify-content: center;
    align-items: center;
}

.product-image-up{
    width: 100%;
    max-width: 450px;
    height: 100%;
    object-fit: cover;
    border-radius: 8px;
    border: 2px solid #b3d9ff;
}
.product-image {
    width: 100%;
    max-width: 450px;
    height: 450px;
    object-fit: cover;
    border-radius: 8px;
    border: 2px solid #b3d9ff;
}

/* 商品信息区域 */
.product-info-section {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.product-title {
    font-size: 2.2rem;
    font-weight: 600;
    color: #1565c0;
    margin: 0;
    line-height: 1.3;
}

.product-category,
.product-price,
.product-stock {
    display: flex;
    align-items: center;
    gap: 12px;
    font-size: 1rem;
}

.category-label,
.price-label,
.stock-label {
    color: #1976d2;
    font-weight: 500;
    min-width: 60px;
}

.category-tag {
    background: #e3f2fd;
    color: #1976d2;
    padding: 4px 12px;
    border-radius: 6px;
    font-size: 0.9rem;
    font-weight: 500;
    border: 1px solid #b3d9ff;
}

.price-value {
    font-size: 1.8rem;
    font-weight: 700;
    color: #1976d2;
}

.stock-value {
    color: #1976d2;
    font-weight: 600;
}

/* 商品描述 */
.product-description {
    margin-top: 15px;
}

.description-title {
    font-size: 1.1rem;
    color: #1565c0;
    margin: 0 0 10px 0;
    font-weight: 600;
}

.description-text {
    color: #424242;
    line-height: 1.6;
    font-size: 0.95rem;
    background: rgba(255, 255, 255, 0.7);
    padding: 16px;
    border-radius: 6px;
    border-left: 3px solid #1976d2;
    margin: 0;
}

/* 购买区域 */
.purchase-section {
    margin-top: 25px;
    padding-top: 25px;
    border-top: 1px solid #b3d9ff;
}

.quantity-selector {
    display: flex;
    align-items: center;
    gap: 16px;
    margin-bottom: 20px;
}

.quantity-label {
    font-size: 1rem;
    color: #1976d2;
    font-weight: 500;
}

.quantity-controls {
    display: flex;
    align-items: center;
    border: 1px solid #b3d9ff;
    border-radius: 6px;
    overflow: hidden;
    background: white;
}

.quantity-btn {
    width: 40px;
    height: 40px;
    border: none;
    background: #e3f2fd;
    color: #1976d2;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.2s ease;
    display: flex;
    align-items: center;
    justify-content: center;
}

.quantity-btn:hover:not(:disabled) {
    background: #1976d2;
    color: white;
}

.quantity-btn:disabled {
    background: #f5f5f5;
    color: #ccc;
    cursor: not-allowed;
}

.quantity-input {
    width: 60px;
    height: 40px;
    border: none;
    text-align: center;
    font-size: 16px;
    font-weight: 500;
    color: #1976d2;
    background: white;
    outline: none;
}

.quantity-input:focus {
    background: #f8f9fa;
}

/* 购买按钮 */
.purchase-actions {
    display: flex;
    justify-content: center;
}

.add-to-cart-btn {
    background: #1976d2;
    color: white;
    border: none;
    padding: 14px 32px;
    border-radius: 6px;
    font-size: 1rem;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;
    min-width: 160px;
}

.add-to-cart-btn:hover:not(:disabled) {
    background: #1565c0;
    transform: translateY(-1px);
}

.add-to-cart-btn:disabled {
    background: #ccc;
    cursor: not-allowed;
    transform: none;
}

/* 商品筛选组件 */
.product-filter-section {
    margin-top: 40px;
    background: rgba(255, 255, 255, 0.6);
    border-radius: 8px;
    border: 1px solid rgba(179, 217, 255, 0.3);
    padding: 30px;
}

.filter-container {
    margin-bottom: 30px;
}

.filter-title {
    font-size: 1.3rem;
    color: #1565c0;
    margin: 0 0 20px 0;
    font-weight: 600;
}

.category-tabs {
    display: flex;
    gap: 12px;
    margin-bottom: 20px;
}

.category-tab {
    padding: 8px 16px;
    background: rgba(255, 255, 255, 0.8);
    border: 1px solid #b3d9ff;
    border-radius: 6px;
    color: #1976d2;
    cursor: pointer;
    transition: all 0.3s ease;
    font-size: 0.9rem;
    font-weight: 500;
}

.category-tab:hover {
    background: #e3f2fd;
    border-color: #1976d2;
    transform: translateY(-1px);
}

.category-tab.active {
    background: #1976d2;
    color: white;
    border-color: #1976d2;
    box-shadow: 0 2px 8px rgba(25, 118, 210, 0.3);
}


/* 筛选结果 */
.filtered-products {
    margin-top: 20px;
}

.results-title {
    font-size: 1.1rem;
    color: #1565c0;
    margin: 0 0 16px 0;
    font-weight: 600;
}

.products-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 16px;
}

.product-item {
    background: white;
    border: 1px solid #b3d9ff;
    border-radius: 8px;
    padding: 12px;
    cursor: pointer;
    transition: all 0.3s ease;
    text-align: center;
}

.product-item:hover {
    border-color: #1976d2;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(25, 118, 210, 0.15);
}

.product-image {
    width: 100%;
    height: 120px;
    margin-bottom: 8px;
    border-radius: 4px;
    overflow: hidden;
}

.product-image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.product-info {
    text-align: left;
}

.product-name {
    font-size: 0.9rem;
    color: #1565c0;
    margin: 0 0 4px 0;
    font-weight: 600;
    line-height: 1.3;
}

.product-category {
    font-size: 0.8rem;
    color: #1976d2;
    margin: 0 0 4px 0;
    background: #e3f2fd;
    padding: 2px 6px;
    border-radius: 4px;
    display: inline-block;
}

.product-price {
    font-size: 0.9rem;
    color: #1976d2;
    margin: 0;
    font-weight: 600;
}


/* 商品不存在 */
.product-not-found {
    text-align: center;
    padding: 60px 20px;
    background: rgba(255, 255, 255, 0.6);
    border-radius: 8px;
    border: 1px solid rgba(179, 217, 255, 0.3);
    max-width: 400px;
    margin: 0 auto;
}

.not-found-icon {
    font-size: 3rem;
    margin-bottom: 16px;
}

.product-not-found h2 {
    font-size: 1.5rem;
    color: #1565c0;
    margin: 0 0 12px 0;
}

.product-not-found p {
    color: #666;
    font-size: 1rem;
    margin: 0 0 24px 0;
    line-height: 1.5;
}

.back-to-list-btn {
    background: #1976d2;
    color: white;
    border: none;
    padding: 12px 24px;
    border-radius: 6px;
    font-size: 0.9rem;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;
}

.back-to-list-btn:hover {
    background: #1565c0;
    transform: translateY(-1px);
}

/* 响应式设计 */
@media (max-width: 768px) {
    .product-detail {
        padding: 15px;
    }
    
    .product-main {
        grid-template-columns: 1fr;
        gap: 30px;
        padding: 30px 20px;
    }
    
    .product-image {
        height: 300px;
    }
    
    .product-title {
        font-size: 1.8rem;
    }
    
    .price-value {
        font-size: 1.5rem;
    }
    
    .quantity-selector {
        flex-direction: column;
        align-items: flex-start;
        gap: 12px;
    }
    
    .quantity-controls {
        width: 100%;
        max-width: 180px;
    }
    
    .add-to-cart-btn {
        width: 100%;
        padding: 12px 24px;
    }
}

@media (max-width: 480px) {
    .product-main {
        padding: 20px 15px;
    }
    
    .product-image {
        height: 250px;
    }
    
    .product-title {
        font-size: 1.6rem;
    }
    
    .back-button {
        padding: 8px 12px;
        font-size: 0.9rem;
    }
    
    .product-filter-section {
        padding: 20px 15px;
    }
    
    .category-tabs {
        flex-wrap: wrap;
        gap: 8px;
    }
    
    .category-tab {
        padding: 6px 12px;
        font-size: 0.85rem;
    }
    
    .products-grid {
        grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
        gap: 12px;
    }
    
    .product-item {
        padding: 8px;
    }
    
    .product-image {
        height: 100px;
    }
}
</style>
